"""
用户相关路由
"""

from fastapi import APIRouter, HTTPException, Depends
from sqlalchemy.orm import Session

from database import get_db
from models.common import StandardResponse
from models.user import User, UserUpdate, UserSettings
from services.auth_service import get_current_user
from services.user_service import UserService

router = APIRouter(prefix="/user", tags=["用户"])

@router.get("/profile", response_model=StandardResponse, summary="获取用户信息")
async def get_user_profile(
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_db)
) -> StandardResponse:
    """
    获取当前用户信息
    """
    try:
        user_service = UserService(db)
        user_info = await user_service.get_user_by_id(current_user["id"])
        
        if not user_info:
            raise HTTPException(
                status_code=404,
                detail="用户不存在"
            )
        
        # 构造响应数据
        user_data = {
            "id": user_info.id,
            "username": user_info.username,
            "name": user_info.name,
            "email": user_info.email,
            "phone": user_info.phone,
            "department": user_info.department,
            "position": user_info.position,
            "avatar": user_info.avatar,
            "status": user_info.status,
            "created_at": user_info.created_at,
            "updated_at": user_info.updated_at
        }
        
        return StandardResponse(
            success=True,
            message="获取用户信息成功",
            data=user_data
        )
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"获取用户信息失败: {str(e)}"
        )

@router.put("/profile", response_model=StandardResponse, summary="更新用户信息")
async def update_user_profile(
    user_update: UserUpdate,
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_db)
) -> StandardResponse:
    """
    更新用户信息
    
    - **name**: 真实姓名
    - **email**: 邮箱
    - **phone**: 手机号
    - **department**: 部门
    - **position**: 职位
    - **avatar**: 头像URL
    """
    try:
        user_service = UserService(db)
        updated_user = await user_service.update_user(
            user_id=current_user["id"],
            user_update=user_update
        )
        
        return StandardResponse(
            success=True,
            message="更新用户信息成功",
            data={
                "id": updated_user.id,
                "username": updated_user.username,
                "name": updated_user.name,
                "email": updated_user.email,
                "phone": updated_user.phone,
                "department": updated_user.department,
                "position": updated_user.position,
                "avatar": updated_user.avatar
            }
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"更新用户信息失败: {str(e)}"
        )

@router.get("/settings", response_model=StandardResponse, summary="获取用户设置")
async def get_user_settings(
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_db)
) -> StandardResponse:
    """
    获取用户设置
    """
    try:
        user_service = UserService(db)
        settings = await user_service.get_user_settings(current_user["id"])
        
        return StandardResponse(
            success=True,
            message="获取用户设置成功",
            data=settings
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"获取用户设置失败: {str(e)}"
        )

@router.put("/settings", response_model=StandardResponse, summary="更新用户设置")
async def update_user_settings(
    settings_update: dict,
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_db)
) -> StandardResponse:
    """
    更新用户设置
    
    - **theme**: 主题设置
    - **language**: 语言设置
    - **notifications_enabled**: 是否启用通知
    - **auto_login**: 是否自动登录
    """
    try:
        user_service = UserService(db)
        updated_settings = await user_service.update_user_settings(
            user_id=current_user["id"],
            settings_data=settings_update
        )
        
        return StandardResponse(
            success=True,
            message="更新用户设置成功",
            data=updated_settings
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"更新用户设置失败: {str(e)}"
        )